<template>
  <a-card>
    <!--操作按钮区域-->
    <div class="btn-style">
      <a-button type="primary" @click="handleAdd">
        <template #icon>
          <PlusOutlined />
        </template>新增
      </a-button>
      <a-button @click="handleAddChild">
        <template #icon>
          <PlusOutlined />
        </template>添加下级
      </a-button>
      <a-upload name="file" :customRequest="handleImport" :showUploadList="false">
        <a-button>
          <template #icon>
            <UploadOutlined />
          </template>导入
        </a-button>
      </a-upload>
      <a-button @click="handleExport">
        <template #icon>
          <DownloadOutlined />
        </template>导出
      </a-button>
    </div>
    <a-tree v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys" :tree-data="treeData"
      :show-line="true">
      <template #title="{ key: treeKey, title, dataRef }">
        <a-dropdown :trigger="['contextmenu']">
          <span>{{ title }}</span>
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="handleAddChildDepend(dataRef)">添加下级</a-menu-item>
              <a-menu-item key="2" @click="handleDelete(treeKey)">
                <span style="color: red">删除</span>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
    </a-tree>
  </a-card>
</template>
<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { getAction } from '@/utils/httpAction';
import { defineEmits } from 'vue';

const url = {
  getDeptTree: '/system/dept/getDeptTree',
}
const model = reactive({
  id: '',
  deptCode: '',
  parentDeptCode: '',
  deptName: '',
  status: true,
  orderNo: '',
})

const treeData = ref();

const expandedKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]);
const emit = defineEmits(['sendData']);

const getDeptTree = async () => {
  treeData.value = await getAction(url.getDeptTree, {});
  // 获取所有节点的key并设置给expandedKeys
  const getAllKeys = (nodes: any[]): string[] => {
    return nodes.reduce((keys: string[], node) => {
      keys.push(node.key);
      if (node.children) {
        keys.push(...getAllKeys(node.children));
      }
      return keys;
    }, []);
  };
  expandedKeys.value = getAllKeys(treeData.value);
}
getDeptTree();


const handleAdd = () => {
  emit('sendData', '');
}

function handleAddChild() {

}

function handleAddChildDepend(dataRef: any) {
  emit('sendData', dataRef.key);
}

async function handleDelete(treeKey: string) {
  console.log(treeKey, '删除部门');

}

const handleImport = () => {
  console.log('导入')
}

const handleExport = () => {
  console.log('导出')
}

watch(selectedKeys, () => {
  if (selectedKeys.value[0]) {
    emit('sendData', selectedKeys.value[0]);
  }
});
</script>